﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformWeb.Models.ReportCenter;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("44")]
    public class DriveStatisticController : Controller
    {
        //
        // GET: /DriveStatistic/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetData(string beginTime, string endTime, List<string> vehicleNums)
        {
            if (!string.IsNullOrEmpty(beginTime) && !string.IsNullOrEmpty(endTime) && vehicleNums != null && vehicleNums.Count == 1)
            {
                string sql = "select vehiclenum id,"
                + "cast(cast(longitudeoffset as decimal(20,8)) as varchar(20)) lng,"
                + "cast(cast(latitudeoffset as decimal(20,8)) as varchar(20)) lat,"
                + "cast(gpsmileage as varchar(10)) gpsMileage,"
                + "cast(mileage as varchar(10)) devMileage,"
                + "recordtime as time,"
                + "statusinfo as state "
                + "from gpsbasic "
                + "where recordtime >= '" + beginTime + "' and recordtime <= '" + endTime + "' and vehicleNum = '" + vehicleNums[0] + "' "
                + "order by recordtime asc";
                string historyStr = RealTimeGet.getReportFromGeoBase(
                    CommonFunctions.GetLoginUser().UserId,
                    sql,
                    beginTime,
                    endTime,
                    "0");
                List<RealTimeModel> modelList = new List<RealTimeModel>();
                List<DriveStatistic> retList = new List<DriveStatistic>();
                if (historyStr != "error" && historyStr != "")
                {
                    try
                    {
                        modelList = CommonFunctions.JsonStrToObject<List<RealTimeModel>>(historyStr);
                        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                        DriveStatistic tmp = new DriveStatistic();
                        int preIndex = -1;
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            RealTimeModel model = modelList[i];
                            CommonFunctions.ParseStateInfo(model, model.state);
                            if (model.state0.Equals("开") && preIndex == -1)
                            {
                                tmp = new DriveStatistic();
                                preIndex = i;
                            }
                            if ((model.state0.Equals("关") && preIndex != -1) || 
                                (model.state0.Equals("开") && i == modelList.Count - 1))
                            {
                                tmp.mNum = model.id;
                                tmp.mStartTime = modelList[preIndex].time;
                                tmp.mEndTime = model.time;
                                tmp.mGpsMileage = (Convert.ToDouble(model.gpsMileage) - Convert.ToDouble(modelList[preIndex].gpsMileage)).ToString("0.00") + "公里";
                                tmp.mDevMileage = (Convert.ToDouble(model.devMileage) - Convert.ToDouble(modelList[preIndex].devMileage)).ToString("0.00") + "公里";
                                tmp.mStartLat = modelList[preIndex].lat;
                                tmp.mStartLng = modelList[preIndex].lng;
                                tmp.mEndLat = model.lat;
                                tmp.mEndLng = model.lng;
                                if (retList.Count < 20)
                                {
                                    tmp.mStartAddr = geoHelper.GgpsTranslate2BaiduPoi(tmp.mStartLng,tmp.mStartLat);
                                    tmp.mEndAddr = geoHelper.GgpsTranslate2BaiduPoi(tmp.mEndLng, tmp.mEndLat);
                                }
                                retList.Add(tmp);
                                preIndex = -1;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
                else
                {
                }
                var json = new
                {
                    total = retList.Count,
                    rows = (from r in retList
                            select r).ToArray()
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        /*解析地理位置*/
        [HttpPost]
        public ActionResult ParseAddr(string key, int page, List<string> lngs, List<string> lats)
        {//key为查询批次的唯一标示，防止前台点击“查询”重新查询另一批数据时，后台处理返回数据与前台数据不唯一
            if (lngs.Count == lats.Count)
            {
                MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                List<string> pois = new List<string>();
                for (int i = 0; i < lngs.Count; i++)
                {
                    if (lngs[i] == "" || lats[i] == "" || lngs[i] == "null" || lats[i] == "null")
                    {
                        pois.Add("");
                    }
                    else
                    {
                        pois.Add(geoHelper.GgpsTranslate2BaiduPoi(lngs[i], lats[i]));
                    }
                }
                var json = new
                {
                    key = key,
                    page = page,
                    pois = (from r in pois
                            select r).ToArray()
                };
                return Json(json);
            }
            return null;
        }

        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportExcel()
        {
            List<DriveStatistic> list = CommonFunctions.JsonStrToObject<List<DriveStatistic>>(Request.Form["data"]);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号","车牌号", "SIM卡号", "单位名称","开始时间","结束时间","持续时长","行驶里程（GPS）","行驶里程（仪表）","开始地点", "结束地点" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mName);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", list[i].mSim);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mDepart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mStartTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mEndTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mInterval);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mGpsMileage);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mDevMileage);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mStartAddr);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mEndAddr);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", list[0].mName + "_" + list[0].mSim + "行车统计.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }
    }
}
